from flask import Blueprint, render_template, request, url_for, redirect
from ..exts import db
from .models import Article, Comment, Message
from .ip2region import search_with_file
blog_bp = Blueprint('blogs', __name__, url_prefix='/blog')


@blog_bp.route('/page/<int:curr>')
def blog_index(curr=1):
    print(request.base_url)
    article_pg = Article.query.paginate(page=curr, per_page=5)
    count = article_pg.total
    return render_template('blogs/index.html', **locals())


@blog_bp.route('/article/<int:article_id>')
def article(article_id):
    article = Article.query.get(article_id)
    if article is None:
        return '404页面'
    article.read_count += 1
    db.session.commit()

    prev_article = Article.query.filter(Article.id < article.id).order_by(Article.id.desc()).first()
    next_article = Article.query.filter(Article.id > article.id).first()

    prev_article = prev_article if prev_article else None
    next_article = next_article if next_article else None

    main_comments = Comment.query.filter_by(article_id=article_id, replied_id=None).order_by(Comment.add_time.desc()).all()

    all_comments = []
    for main_comment in main_comments:
        replies = get_replies(comment_id=main_comment.id, reply_target_name=None)
        # 时间降序
        replies = sorted(replies, key=lambda x: x['add_time'], reverse=True)
        comment_data = {
            'id': main_comment.id,
            'content': main_comment.content,
            'visitor_name': main_comment.visitor_name,
            'visitor_address': main_comment.visitor_address,
            'add_time': main_comment.add_time,
            'replies': replies
        }
        all_comments.append(comment_data)

    return render_template('blogs/articles.html', **locals())


def get_replies(comment_id, reply_target_name):
    # 获取特定评论的所有子评论
    replies = Comment.query.filter_by(replied_id=comment_id).all()

    # 递归处理子评论的子评论
    reply_data = []
    for reply in replies:
        reply_data.append({
            'id': reply.id,
            'content': reply.content,
            'visitor_name': reply.visitor_name,
            'visitor_address': reply.visitor_address,
            'add_time': reply.add_time,
            'reply_target_name': reply_target_name
        })
        reply_data.extend(get_replies(comment_id=reply.id, reply_target_name=reply.visitor_name))
    return reply_data


@blog_bp.route('/comment_add', methods=['POST'])
def comment_add():
    form_data = request.form
    visitor_ip = request.remote_addr
    visitor_address = search_with_file(visitor_ip)

    comment = Comment(
        content=form_data['content'],
        visitor_name=form_data['name'],
        visitor_email=form_data['email'],
        visitor_ip=visitor_ip,
        visitor_address=visitor_address,
        article_id=form_data['article_id']
    )

    db.session.add(comment)
    db.session.commit()
    return 'success'


@blog_bp.route('/comment_reply', methods=['POST'])
def comment_reply():
    form_data = request.form
    visitor_ip = request.remote_addr
    visitor_address = search_with_file(visitor_ip)

    comment = Comment(
        content=form_data['content'],
        visitor_name=form_data['name'],
        visitor_email=form_data['email'],
        visitor_ip=visitor_ip,
        visitor_address=visitor_address,
        post_id=form_data['post_id'],
        replied_id=form_data['replied_id']
    )
    db.session.add(comment)
    db.session.commit()
    return 'success'


@blog_bp.route('/record')
def record():
    articles = Article.query.filter_by(draft_flag=False).order_by(Article.add_time.desc()).all()
    record_dict = {}
    for article in articles:
        date = article.add_time.strftime("%Y-%m")
        record_dict.setdefault(date, []).append(article)
    for i in record_dict.items():
        print(i)
    print(record_dict)
    return render_template('blogs/record.html', **locals())


@blog_bp.route('/note')
def note():
    return render_template('blogs/note.html')


@blog_bp.route('/message')
def message():
    messages = Message.query.order_by(Message.add_time.desc()).all()
    return render_template('blogs/message.html', messages=messages)


@blog_bp.route('/message_add', methods=['POST'])
def message_add():
    form_data = request.form
    visitor_ip = request.remote_addr
    visitor_address = search_with_file(visitor_ip)
    message = Message(
        content=form_data['comment'],
        visitor_name=form_data['name'],
        visitor_email=form_data['email'],
        visitor_ip=visitor_ip,
        visitor_address=visitor_address,
    )
    db.session.add(message)
    db.session.commit()
    return 'success'


@blog_bp.route('/about')
def about():
    return render_template('blogs/about.html')